//
//  DownloadVideoManager.m
//  MVideo
//
//  Created by Lin Eidan on 14-4-1.
//  Copyright (c) 2014年 taomee. All rights reserved.
//

#import "M3U8DownloadConfig.h"
#import "config.h"
#import "Header.h"
#import "LocalFileManage.h"
#import "VideoObj.h"
#import "UserDataBasic.h"



@interface DownloadVideoManager ()

//后台下载
@property (assign, nonatomic) BOOL isInBackground;
@property (assign, nonatomic) int nextStartIndex;
@property (assign, nonatomic) BOOL isCanStartNextOne;

//ios6
@property (assign, nonatomic) int ios6BackgroundDownloadStopIndex;


@end

@implementation DownloadVideoManager

+ (DownloadVideoManager *)sharedInstance
{
    
    static DownloadVideoManager *_sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[DownloadVideoManager alloc] init];
    });
    return _sharedInstance;
}



-(id)init{
    if (self =[super init]) {
        self.isInBackground = NO;
        self.ios6BackgroundDownloadStopIndex = -1;
        self.downloadQueue = [UserDataBasic readObjectArrayForKey:DownloadVideoQueue];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppTerminate) name:UIApplicationWillTerminateNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleWhenAppWillEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
    }
    return self;
}

-(void)addTheVideoToDownloadQueueWith:(VideoObj *)downVideoObj{
    [self.downloadQueue addObject:downVideoObj];
    downVideoObj.isInDownload = YES;
}

-(void)startDownload{
    [self startTheClosestItemFromThisOneWithIndex:0];
    [self saveDowningQueueToLocal];
}

//从特定的某一集开始下载，如果有正在下载的，就先暂停那个，开始这个。
-(void)startDownloadTheVideoWithObj:(VideoObj *)obj{
    [self removeAllDownloadRequest];
    [self thisEpisodeIsCanStartDownLoadRightNow:obj];
}

#pragma mark -点击处理和取消请求和删除
-(void)downloadCellHasClicked:(int )index{
    VideoObj *obj = [self.downloadQueue objectAtIndex:index];
    [self downloadCellHasClickedWithObj:obj];
}

-(void)downloadCellHasClickedWithObj:(VideoObj *)obj{
    if (obj.isLoading) {    //点击暂停。
        obj.isLoading = NO;
        [self cancelRequestWithObj:obj];
        [self downloadItmeFailedHandleWith:obj];
        
    }else{  //目前暂停，点击开始，当然要暂停其他的项。。
        [self removeAllDownloadRequest];
        [self thisEpisodeIsCanStartDownLoadRightNow:obj];
    }
}

-(void)cancelRequestWithObj:(VideoObj *)obj{
    
    if (IsNull(obj)) {
        return;
    }
    
    //public
    [obj.m3u8DownloadManage pauseDownloadVideo];
    
    //ios6
    if (obj.requestOperaiton) {
        [obj.requestOperaiton cancel];
    }
    
    if (obj.downTask && isiOS7) {
        //ios7
        if (obj.allowResume) {
            [obj.downTask cancelByProducingResumeData:^(NSData *resumeData) {
                obj.downTaskResumeData = resumeData;
            }];
        }else{
            [obj.downTask cancel];
        }
    }
    [[DownloadGetData sharedInstance] removeAllDownloadRelatedRequest];
    
}

//清除所有请求
- (void)removeAllDownloadRequest{
    for (VideoObj *obj in self.downloadQueue) {
        if (obj.isLoading) {
            [self cancelRequestWithObj:obj];
            [self downloadItmeFailedHandleWith:obj];
        }
    }
}

//删除的需要处理。。。
//把要删除的项存在一个数组一起传进来。
-(void)deleteTheDownloadItemsWithRemoveArray:(NSArray *)removeArray andIsDownloading:(BOOL)isDownloading{
    if (isDownloading) {  //正在下载的
        for (VideoObj *obj in removeArray) {
            if (obj.isLoading) {
                [self cancelRequestWithObj:obj];
            }
            
//            [self.downloadQueue removeObject:obj];
            
            obj.isComplete = NO;
            obj.isLoading = NO;
            obj.percent = 0.0;
            obj.percentLast = 0.0;
            obj.contentLength = 0.0;
            
            [self deleteFileWithObj:obj];
            
            if (isiOS7) {  //删除mp4缓存文件
                if (obj.downTaskResumeData) {
                    //这边还要删除它的tmp文件。。
                    [[DownloadGetData sharedInstance] deleteTheTempFileWithResumeData:obj.downTaskResumeData];
                }else{
                    if (obj.downTaskResumeData) {
                        //这边还要删除它的tmp文件。。
                        [[DownloadGetData sharedInstance] deleteTheTempFileWithResumeData:obj.downTaskResumeData];
                    }
                }
                obj.downTaskResumeData = nil;  //这边记得清空
            }else{
                if (obj.requestTempFilePath) {  //ios6 删除缓存文件
                    [LocalFileManage deleteFile:obj.requestTempFilePath];
                }
            }

        }
        
        [self saveDowningQueueToLocal];
    }else{
//        for (DSuccessVideoObj *successObj in removeArray) {
//            [self.successQueue removeObject:successObj];
//            for (VideoObj *obj in successObj.sameContentIdDownloadObjsArray) {
//                [self deleteFileWithObj:obj];
//            }
//        }
    }
    //这里本来应该要开始其他项的，但有bug，所以延迟一下，在退出编辑模式的时候，开始其他项。。，功能达到了就行。。
}

//删除成功具体页面里面的具体剧集。
-(void)deleteTheDownloadSuccessContentIdDetailItemsWithId:(NSString *)detailId andRemoveArray:(NSArray *)removeArray{
//    DSuccessVideoObj *temp;
//    for (DSuccessVideoObj *successObj in self.successQueue) {
//        if ([successObj.contentId isEqualToString:detailId]) {
//            temp = successObj;
//            break;
//        }
//    }
//    
//    for (VideoObj *obj in removeArray) {
//        [temp.sameContentIdDownloadObjsArray removeObject:obj];
//        [self deleteFileWithObj:obj];
//    }
//    
//    if (temp.sameContentIdDownloadObjsArray.count == 0) {
//        [self.successQueue removeObject:temp];
//    }
}

-(void)deleteFileWithObj:(VideoObj *)obj{
    NSString *downloadPathNew = [self getEpisodeFilePathWithContentId:obj.contentId andEpisodeId:obj.episodeId andNeedCreateFolder:NO];
    [LocalFileManage deleteFile:downloadPathNew];
}

#pragma mark -开始清求数据

//查找最靠前，且还没完成下载，并且还是可以自动开始状态
-(void)startTheClosestItemFromThisOneWithIndex:(int )index{
    
    if ([self isHasObjInLoading]) {
        return;
    }
    
    if (index >  self.downloadQueue.count - 1) {  //从头开始
        index = 0;
    }
    
    for (int i=index; i<self.downloadQueue.count; i++) {
        VideoObj *obj=[self.downloadQueue objectAtIndex:i];
        if (!obj.isLoading && obj.isReadyShow && !obj.isComplete && !obj.isNeedVIP) {
            [self thisEpisodeIsCanStartDownLoadRightNow:obj];
            break;
        }
    }
}

-(void)thisEpisodeIsCanStartDownLoadRightNow:(VideoObj *)obj{
    if ([[kHandle sharedInstance] isShouldToDisplayTheTipsWithDownloadInThe3G]) {
        [PopTips tips:kApp.rootNav.view Msg:TipsHandleDowanloadIn3GText];
    }else{
        obj.isLoading = YES;
        
        if (!self.isInBackground && [self.delegate respondsToSelector:@selector(updateStartDownLoadUIInTheItemWithIndex:)]) {
            [self.delegate updateStartDownLoadUIInTheItemWithIndex:[self getTheObjIndex:obj]];
        }
        
        NSString * url = [NSString stringWithFormat:@"%@getVideoUrl&pf=2&id=%@",API_BASE,obj.episodeId];
        [self startGetDetailDataWithURL:url andObj:obj];
        [self saveDowningQueueToLocal];
    }
}

-(void)startGetDetailDataWithURL:(NSString *)url andObj:(VideoObj *)obj{
    if (isiOS7) {
        
        NSString *downloadPath= [self getEpisodeFilePathWithContentId:obj.contentId andEpisodeId:obj.episodeId andNeedCreateFolder:YES];
        NSString *fileName = [[NSString alloc] initWithFormat:@"%@_%@.json",obj.contentId,obj.episodeId];
        
        self.isCanStartNextOne = NO;
//        NSLog(@"m ,%d",self.isCanStartNextOne);
        
        [[DownloadGetData sharedInstance] startTaskBackgroundDataGet:url andFileFolderPath:downloadPath andFileName:fileName andResultIsJSON:YES andTaskCompletion:^(NSURLResponse *response, id responseObj, BOOL isSuccess) {
            if (isSuccess) {
                [self getPlayDetailDataSuccess:responseObj andObj:obj];
            }else{
                [self getPlayDetailDataFailedWithObj:obj];
            }
        }];
        
//        [[DownloadGetData sharedInstance] startGet:url andResultIsJSON:YES andTaskCompletion:^(NSURLSessionDataTask *task, id responseObj, BOOL isSuccess) {
//            if (isSuccess) {
//                [self getPlayDetailDataSuccess:responseObj andObj:obj];
//            }else{
//                [self getPlayDetailDataFailedWithObj:obj];
//            }
//            
//        }];
        

    }else{
        [[DownloadGetData sharedInstance] startGet:url andResultIsJSON:YES andCompletion:^(AFHTTPRequestOperation *operation, id responseObj, BOOL isSuccess) {
            if (isSuccess) {
                [self getPlayDetailDataSuccess:responseObj andObj:obj];
            }else{
                [self getPlayDetailDataFailedWithObj:obj];
            }
        }];
    }
}

-(void)getPlayDetailDataSuccess:(id)responseJSON andObj:(VideoObj *)obj{
//   NSLog(@"q ,%d",self.isCanStartNextOne);
    if (!obj.isLoading && !self.isInBackground) {
        //点击暂停，isLoading肯定为No，但是Request还没有取消掉，可能会继续下载，这里多一层判断，保证其不会下载。
        return;
    }
    
    NSDictionary *detailInfo = responseJSON;
    NSDictionary *urlInfo = [detailInfo objectForKey:@"url"];
    
    obj.sourceType = [urlInfo objectForKey:@"type"];
    obj.downloadRequestURL = [urlInfo objectForKey:@"url"];
    
    if (IsNull(obj.downloadRequestURL) || IsNull(obj.sourceType)) {
        [self downloadItmeFailedHandleWith:obj];
        return;
    }
    
    if ([obj.sourceType isEqualToString:VideoTypeM3U8]) {
        [self createTheM3U8HandleWithObj:obj];
    }else{
        [self createMP4HandleWithObj:obj];
    }
    NSLog(@"%@",urlInfo);
    
    [self saveDowningQueueToLocal];
}

-(void)getPlayDetailDataFailedWithObj:(VideoObj *)obj{
    [self downloadItmeFailedHandleWith:obj];
}



#pragma mark -mp4
-(void)createMP4HandleWithObj:(VideoObj *)obj{
//    NSLog(@"%@",obj.downloadRequestURL);
    
    NSString *downloadPath= [self getEpisodeFilePathWithContentId:obj.contentId andEpisodeId:obj.episodeId andNeedCreateFolder:YES];
    NSString *segmentPrefix = [self getLocalServerRequestFolderPathWithContentId:obj.contentId andEpisodeId:obj.episodeId];
    
    NSString *fileName = [[NSString alloc] initWithFormat:@"%@_%@.mp4",obj.contentId,obj.episodeId];
    NSString *filePath=[downloadPath stringByAppendingPathComponent:fileName];
    obj.playURL =[segmentPrefix stringByAppendingPathComponent:fileName];
    
    if (isiOS7) {
       
        obj.downTask = [[DownloadGetData sharedInstance] startTaskBackgroundDownload:obj.downloadRequestURL andFileFolderPath:downloadPath andFileName:fileName andAllowResume:obj.allowResume andStartRightNow:YES andResumeData:obj.downTaskResumeData andProgress:^(NSURLSessionDownloadTask *task, float percent) {
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                if (percent > obj.percent) {
                    obj.percent = percent;
                }
                 
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self updateDownloadPerWith:obj];
                });
            });
            
        } andCompletion:^(NSURLResponse *response,long long contentLength, BOOL isSuccess) {
            if (isSuccess) {
                [self handleWhenVideoDownloadSuccess:obj andContentLength:contentLength];
            }else{
                [self downloadItmeFailedHandleWith:obj];
            }
        }];
        
        //让每一个task都有唯一标示，才能让其在不正常退出的时候，resumeData能够给到他。
        obj.downTask.taskDescription = obj.episodeId;
       
    }else{
        obj.requestOperaiton =  [[DownloadGetData sharedInstance] startDownload:obj.downloadRequestURL andFilePath:filePath andAllowResume:obj.allowResume andProgress:^(AFDownloadRequestOperation *operation, float percent, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if (percent > obj.percent) {
                    obj.percent = percent;
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self updateDownloadPerWith:obj];
                });
            });
        } andCompletion:^(AFHTTPRequestOperation *operation, long long contentLength, BOOL isSuccess) {
            if (isSuccess) {
                [self handleWhenVideoDownloadSuccess:obj andContentLength:contentLength];
            }else{
                [self downloadItmeFailedHandleWith:obj];
            }
        }];
        obj.requestTempFilePath = obj.requestOperaiton.tempPath;
    }
    
    
}


-(void)handleWhenVideoDownloadSuccess:(VideoObj *)VideoObj andContentLength:(long long)contentLength{
//    NSLog(@"success");
    self.isCanStartNextOne = YES;
    
    VideoObj.isLoading = NO;
    VideoObj.isComplete = YES;
    VideoObj.isInDownload = YES;
    VideoObj.percent = 1.0f;
    VideoObj.contentLength = contentLength;
    
    int flag = [self getTheObjIndex:VideoObj];
    self.nextStartIndex = flag;
    
    
    if (!self.isInBackground && [self.delegate respondsToSelector:@selector(updateHasDownloadPer:inTheItemWithIndex:)]) {
        [self.delegate updateHasDownloadPer:1 inTheItemWithIndex:flag];
    }
    
    if (!self.isInBackground && [self.delegate respondsToSelector:@selector(updateSuccessUIInTheItemWithIndex:)]) {
        [self.delegate updateSuccessUIInTheItemWithIndex:flag];
    }
    
    if (!self.isInBackground || !isiOS7) {
        [self startTheClosestItemFromThisOneWithIndex:flag];
    }
    
    
    //存本地
    [self handleTheSuccessArrayWith:VideoObj];
    [self saveDowningQueueToLocal];
    VideoObj.m3u8DownloadManage.delegate = nil;
}


#pragma mark -m3u8
-(void)createTheM3U8HandleWithObj:(VideoObj *)obj{
//    NSLog(@"m3u8 start");
    obj.m3u8Handle = [[M3U8Handle alloc] initWithDownloadObj:obj];
    obj.m3u8Handle.delegate=self;
    
    if ([obj.downloadRequestURL isKindOfClass:[NSString class]]) {  //m3u8
        [obj.m3u8Handle parseURL:obj.downloadRequestURL];
    }else{
        [obj.m3u8Handle parseURLArray:obj.downloadRequestURL];  //cartoon
    }
}

-(void)m3U8HandleSuccessed:(M3U8Handle *)m3U8Handle andIsCartoon:(BOOL)isCartoon andVideoObj:(VideoObj *)VideoObj{
    if (!VideoObj.isLoading && !self.isInBackground) {
        return;
    }
    VideoObj.m3u8DownloadManage = [[M3U8DownloadManage alloc] initWithM3U8Handle:m3U8Handle andVideoObj:VideoObj];
    VideoObj.m3u8DownloadManage.delegate = self;
    
    id localVideoPlayURL = m3U8Handle.localHttpServerM3U8FilePath;  //字符串
    if (isCartoon) {
        localVideoPlayURL = m3U8Handle.cartoonPicInLocalServerURLArray;  //数组
    }
    VideoObj.playURL = localVideoPlayURL;
    
    [VideoObj.m3u8DownloadManage startDownloadVideo];
}

-(void)m3U8HandleFailed:(M3U8Handle *)m3U8Handle andVideoObj:(VideoObj *)VideoObj{
    [self downloadItmeFailedHandleWith:VideoObj];
    VideoObj.m3u8Handle.delegate = nil;
}

//百分比
-(void)m3U8DownloadManage:(M3U8DownloadManage *)m3U8DownloadManage andAllSegmentsHasDownloadPer:(float)per andVideoObj:(VideoObj *)VideoObj{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if (per > VideoObj.percent) {
            VideoObj.percent = per;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateDownloadPerWith:VideoObj];
        });
    });
}

//failed
-(void)m3U8DownloadManageAllSegmentsHasDownloadFailed:(M3U8DownloadManage *)m3U8DownloadManage andVideoObj:(VideoObj *)VideoObj{
    [self downloadItmeFailedHandleWith:VideoObj];
}

//success
-(void)m3U8DownloadManageAllSegmentsHasDownloadSuccessed:(M3U8DownloadManage *)m3U8DownloadManage andVideoObj:(VideoObj *)VideoObj{
    NSString *downloadPath=[self getEpisodeFilePathWithContentId:VideoObj.contentId andEpisodeId:VideoObj.episodeId andNeedCreateFolder:NO];
    [self handleWhenVideoDownloadSuccess:VideoObj andContentLength:[LocalFileManage folderSizeAtPath:downloadPath]];
}

#pragma mark -成功失败的状态处理

-(void)updateDownloadPerWith:(VideoObj *)obj{
    
    if (obj.percent >= obj.percentLast + 0.01) {  //防止过于频繁刷UI。
        obj.percentLast = obj.percent;
    }else{
        return;
    }
    if (!self.isInBackground) {
        int flag = [self getTheObjIndex:obj];
        if (flag >= 0) {
            if ( [self.delegate respondsToSelector:@selector(updateHasDownloadPer:inTheItemWithIndex:)]) {
                if (obj.percent > 1) {
                    obj.percent=1;
                }
                [self.delegate updateHasDownloadPer:obj.percent inTheItemWithIndex:flag];
            }
        }
    }
    [self handleTheNoEnoughSpace];
}

//点击暂停，或者自动下载失败调用
-(void)downloadItmeFailedHandleWith:(VideoObj *)obj{
    obj.isLoading = NO;
    if (!self.isInBackground && [self.delegate respondsToSelector:@selector(updateFailedUIInTheItemWithIndex:)]) {
        [self.delegate updateFailedUIInTheItemWithIndex:[self getTheObjIndex:obj]];
    }
    obj.m3u8DownloadManage.delegate = nil;
    [self saveDowningQueueToLocal];
}

-(void)handleTheSuccessArrayWith:(VideoObj *)obj{
//    for (int i=0; i<self.successQueue.count; i++) {
//        DSuccessVideoObj *dSuccessObj = [self.successQueue objectAtIndex:i];
//        if ([dSuccessObj.contentId isEqualToString:obj.contentId]) {
//            [dSuccessObj.sameContentIdDownloadObjsArray addObject:obj];
//            [UserDataBasic saveThisObjectArray:self.successQueue forArrayKey:SuccessVideoQueue];
//            return;
//        }
//    }
//    
//    //如果没有找到
//    DSuccessVideoObj *dSuccessObj = [[DSuccessVideoObj alloc] init];
//    dSuccessObj.contentId = obj.contentId;
//    [dSuccessObj.sameContentIdDownloadObjsArray addObject:obj];
//    [self.successQueue addObject:dSuccessObj];
//    [self saveSuccessQueueToLocal];
}


#pragma mark -后台处理

-(void)handleWhenAppTerminate{
    [UserDataBasic saveThisObjectArray:self.downloadQueue forArrayKey:DownloadVideoQueue];
}

//处理上一次不正常退出，让上一次本来在下载的项继续下载。。
-(void)handleTheLastTerminate{
    for (VideoObj *obj in self.downloadQueue) {
        if (obj.isLoading) {
            obj.isLoading = NO;
            [self saveDowningQueueToLocal];
//            [self thisEpisodeIsCanStartDownLoadRightNow:obj];
            break;
        }
    }
}

-(void)handleWhenAppDidEnterBackground{
    self.isInBackground = YES;
    if (!isiOS7) {
        [self endBackgroundTask];
        VideoObj *obj = [self getCurrentLoadingObj];  //ios6有正在下载的，那么就可以后台下载
        if (obj) {
            kApp.downLoadTaskIdentifer=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
                self.ios6BackgroundDownloadStopIndex = [self getTheLoadingObjIndex];  //记录10分钟后，程序杀掉的时候，刚好下到哪个index。
                [self cancelRequestWithObj:[self getCurrentLoadingObj]];
                [self endBackgroundTask];
            }];
        }
    }else{
        
    }
}

-(void)handleWhenAppWillEnterForeground{
    if (self.isInBackground) {
        self.isInBackground = NO;
        
        if ([self.delegate respondsToSelector:@selector(updateListViewUI)]) {
            [self.delegate updateListViewUI];
        }
        
        if (!isiOS7 && self.ios6BackgroundDownloadStopIndex >= 0) {  //从哪开始下载
            [self startTheClosestItemFromThisOneWithIndex:self.ios6BackgroundDownloadStopIndex];
            self.ios6BackgroundDownloadStopIndex = -1;
        }
        
    }
}

-(void)endBackgroundTask{
    [[UIApplication sharedApplication] endBackgroundTask:kApp.downLoadTaskIdentifer];
    kApp.downLoadTaskIdentifer = UIBackgroundTaskInvalid;
}

-(void)backgrondDownloadOneTaskComplete{
    if (self.isCanStartNextOne) {
        //        NSLog(@"can");
        [self delayToStartNextOne];
    }else{
        //         NSLog(@"cannot ");
        [self delayToHandleCompleting];
    }
}

-(void)delayToStartNextOne{
    [self startTheClosestItemFromThisOneWithIndex:self.nextStartIndex];
    [self delayToHandleCompleting];
}

-(void)delayToHandleCompleting{
    void (^completionHandler)() = kApp.backgroundSessionCompletionHandler;
    kApp.backgroundSessionCompletionHandler = nil;
    completionHandler();
}



#pragma mark -public

-(NSMutableArray *)createLocalPlayListArrayWithObj:(VideoObj *)obj{
//    for (DSuccessVideoObj *successObj in self.successQueue) {
//        if ([successObj.contentId isEqualToString:obj.contentId]) {
//            NSArray *tempArray= successObj.sameContentIdDownloadObjsArray;
//            NSMutableArray *playListArray = [[NSMutableArray alloc] init];
//            
//            if (tempArray.count <= 1) {
//                return nil;
//            }
//            
//            int endIndex = obj.currentPlayIndex + tempArray.count;
//            
//            if ([obj.type isEqualToString:VideoTypeNormal] || [obj.type isEqualToString:VideoTypeM3U8]) {
//                for (int i=0; i< endIndex; i++) {
//                    NSString *episodeId = @"-1";
//                    NSString *episdoeName = obj.contentName;
//                    for (VideoObj *cur in tempArray) {
//                        if (cur.currentPlayIndex == i) {
//                            episodeId = cur.episodeId;
//                            episdoeName = cur.episodeName;
//                            break;
//                        }
//                    }
//                    NSDictionary *dic = @{HttpEveryEpisodeId: episodeId,HttpEveryEpisodeHave:@"1",HttpEveryEpisodeName:episdoeName};
//                    [playListArray addObject:dic];
//                }
//            }else{
//                for (int i=0; i< endIndex; i++) {
//                    NSString *episodeId = @"-1";
//                    NSString *episdoeName = obj.contentName;
//                    for (VideoObj *cur in tempArray) {
//                        if (cur.currentPlayIndex == i && [cur.type isEqualToString:obj.type]) {
//                            episodeId = cur.episodeId;
//                            episdoeName = cur.episodeName;
//                            break;
//                        }
//                    }
//                    NSDictionary *dic = @{CTHttpEEId: episodeId,CTHttpEEName:episdoeName};
//                    [playListArray addObject:dic];
//                }
//
//            }
//            return playListArray;
//        }
//    }
    return nil;
}


//在成功的队列里查找，看是否在里面，如果最后一个参数为YES，那么也会在正在下载的队列里寻找。
-(BOOL)findTheEpisodeIsInSuccessQueueWithContentId:(NSString *)contentId andEpisodeId:(NSString *)episodeId andIsNeedToFindInDowningQueue:(BOOL)isNeedFindInDowingQueue{
    BOOL isHave = NO;
    
    for (VideoObj *obj in self.downloadQueue) {
        if ([obj.episodeId isEqualToString:episodeId] && obj.isComplete) {
            isHave = YES;
            break;
        }
    }
    
    //找完成功队列，如果还没找到，且又需要去找正在下载的队列
    if (!isHave && isNeedFindInDowingQueue) {
        for (VideoObj *obj in self.downloadQueue) {
            if ([obj.episodeId isEqualToString:episodeId]) {
                isHave = YES;
                break;
            }
        }

    }
    return isHave;
}

-(NSString *)getVideoFilePathWithContentId:(NSString *)contentId andNeedCreateFolder:(BOOL)isNeed{
    NSString *folderPath=[LocalFileManage getPathInsideLibraryCachesFolder:kPathVideoDownload];
    NSString *contentIdPath= [folderPath stringByAppendingPathComponent:contentId];
    
    if (![LocalFileManage isExistFile:contentIdPath] && isNeed) {  //创建contenId目录。。
        [LocalFileManage createFolder:contentIdPath];
    }
    
    return contentIdPath;
}

-(NSString *)getEpisodeFilePathWithContentId:(NSString *)contentId andEpisodeId:(NSString *)episodeId andNeedCreateFolder:(BOOL)isNeed{
    
    NSString *contentIdPath = [self getVideoFilePathWithContentId:contentId andNeedCreateFolder:isNeed];
    NSString *episodeIdPath=[contentIdPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",episodeId]];
    
    if (![LocalFileManage isExistFile:episodeIdPath] && isNeed) {
        [LocalFileManage createFolder:episodeIdPath];
    }
    
    return episodeIdPath;
}

-(NSString *)getLocalServerRequestFolderPathWithContentId:(NSString *)contentId andEpisodeId:(NSString *)episodeId{
    NSString* segmentPrefix = [NSString stringWithFormat:@"http://127.0.0.1:%d/%@/%@/",kPort,contentId,episodeId];
    return segmentPrefix;
}

-(VideoObj *)getTheObjFromSuccessQueueWithContentId:(NSString *)contentId andEpisodeId:(NSString *)episodeId{
    for (VideoObj *obj in self.downloadQueue) {
        if ([obj.episodeId isEqualToString:episodeId] && obj.isComplete) {
            return obj;
        }
    }
    return nil;
}

-(int)getTheObjIndex:(VideoObj *)obj{
    int flag=-1;
    for (int i=0; i<self.downloadQueue.count; i++) {
        VideoObj *temp = [self.downloadQueue objectAtIndex:i];
        if (temp == obj) {
            flag=i;
            break;
        }
    }
    return flag;
}

-(int)getTheLoadingObjIndex{
    int flag=-1;
    for (int i=0; i<self.downloadQueue.count; i++) {
        VideoObj *temp = [self.downloadQueue objectAtIndex:i];
        if (temp.isLoading) {
            flag=i;
            break;
        }
    }
    return flag;
}


-(BOOL)isHasObjInLoading{
    BOOL isHas = NO;
    for (VideoObj *obj in self.downloadQueue) {
        if (obj.isLoading) {
            isHas = YES;
            break;
        }
    }
    return isHas;
}

-(VideoObj *)getCurrentLoadingObj{
    for (VideoObj *obj in self.downloadQueue) {
        if (obj.isLoading) {
            return obj;
        }
    }
    return nil;
}

-(void)handleTheNoEnoughSpace{
    float freeDiskSpace=[LocalFileManage freeDiskSpace];
    if (freeDiskSpace < MinFreeDiskSpace) {
        if (!self.isInBackground) {
            [PopTips tips:kApp.rootNav.view Msg:@"下载空间不足，请删除一些文件！"];
        }
        [self removeAllDownloadRequest];
    }
}

-(void)saveQueueToLocal{
    [self saveDowningQueueToLocal];
}

-(void)saveDowningQueueToLocal{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [UserDataBasic saveThisObjectArray:self.downloadQueue forArrayKey:DownloadVideoQueue];
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    });
}



@end
